import pymysql
from flask import current_app

def connect_db(host, user, passwd, db):
    conn = pymysql.connect(host,
            user, passwd, db, charset="utf8", use_unicode=True)
    return conn

def get_db():
    app = current_app._get_current_object()
    if hasattr(app,"_dbconn1"):
        try:
            check_db_connection(app._dbconn1)
            app.logger.debug("got the connection from cache")
            return app._dbconn1
        except:
            app.logger.debug("lost the connection to db")
            try:
                app._dbconn1.close()
            except:
                pass
    app.logger.debug("connect to the database...")
    app._dbconn1 = connect_db(**app.config["DB_CONFIG1"])
    return app._dbconn1

def get_db2():
    app = current_app._get_current_object()
    if hasattr(app,"_dbconn2"):
        try:
            check_db_connection(app._dbconn2)
            app.logger.debug("got the connection2 from cache")
            return app._dbconn2
        except:
            app.logger.debug("lost the connection to db2")
            try:
                app._dbconn2.close()
            except:
                pass
    app.logger.debug("connect to the db2...")
    app._dbconn2 = connect_db(**app.config["DB_CONFIG2"])
    return app._dbconn2

def check_db_connection(conn):
    cur = conn.cursor()
    cur.execute("select 1+1 from dual where 0 > 1")
    cur.fetchall()
    cur.close()
    try:
        conn.commit()
    except:
        pass
